//
//  RSSParser.m
//  LiveDailyNews
//
//  Created by smu on 11-7-21.
//  Copyright 2011年 duk. All rights reserved.
//

#import "RSSParser.h"
#import "RSSItem.h"


@implementation RSSParser
@synthesize rssItemData;
@synthesize currentParseBatch;
@synthesize currentParsedCharacterData;
@synthesize currentRSSItemObject;


- (id) init{
	self = [super init];
	if (self) {
		success = NO;
		loading = NO;
		parsed = NO;
        parseFlag = NO;
	}
	return self;
}

- (void)parse:(NSString *)url withDelegate:(id)sender onComplete:(SEL)callback
{
    parentDelegate = sender;
    onCompleteCallback = callback;
    requestUrl = [url retain];
    loading = YES;
    
    //网络下载xml
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[[NSURL alloc] initWithString:requestUrl]];
    [request setHTTPMethod:@"GET"];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [request release];
    
    rssItemData = [[NSMutableData data] retain];
    
}


- (void)parseResponse
{
    self.currentParseBatch = [NSMutableArray array];
    self.currentParsedCharacterData = [NSMutableString string];
    
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:rssItemData];
    
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    [parser setDelegate:self];
    
    [parser parse];
   
    
    [parser release];
    
    
    
    if ([parentDelegate respondsToSelector:onCompleteCallback]) {
		[parentDelegate performSelector:onCompleteCallback withObject:self];
	}

    self.currentParseBatch = nil;
    self.currentRSSItemObject = nil;
    self.currentParsedCharacterData = nil;
}


- (NSMutableArray *)getItems
{
    return currentParseBatch;
}



#pragma mark -
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSLog(@"RSSParser: Response is an NSHTTPURLResponse: Response=%d",[httpResponse statusCode]);
        if ([httpResponse statusCode] >= 400 && [httpResponse statusCode] <= 599) {
            success = NO;
        } else if([httpResponse statusCode] >= 100 && [httpResponse statusCode] <= 299) {
            success = YES;
        } else {
            NSLog(@"RSSParser: Status code is unknown.");
        }
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [rssItemData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSString *dataString = [[[NSString alloc] initWithData:
                             rssItemData encoding:NSUnicodeStringEncoding] autorelease];
    if ([dataString length] > 0) {
        [self parseResponse];
    } 
    loading = NO;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    success = NO;
    loading = NO;
    
    if ([parentDelegate respondsToSelector:onCompleteCallback]) {
        [parentDelegate performSelector:onCompleteCallback withObject:self];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    success = NO;
}


#pragma mark -
#pragma mark Parser constants

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    
}

//发现元素开始符的处理函数  （即报告元素的开始以及元素的属性） 
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"item"]) {
        RSSItem *rssItem = [[RSSItem alloc] init];
        self.currentRSSItemObject = rssItem;
        [rssItem release];
        parseFlag = YES;
    } else if ([elementName isEqualToString:@"enclosure"]){
        //获得图片路径
        NSString *urlAttribute = [attributeDict valueForKey:@"url"];
        self.currentRSSItemObject.imagePath = urlAttribute;
    } else if ([elementName isEqualToString:@"title"] ||
               [elementName isEqualToString:@"link"] ||
               [elementName isEqualToString:@"category"] ||
               [elementName isEqualToString:@"description"] ||
               [elementName isEqualToString:@"pubDate"]) {
        [currentParsedCharacterData setString:@""];

    }
}

//处理标签包含内容字符 （报告元素的所有或部分内容）

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (parseFlag) {
//        [self.currentParsedCharacterData setString:string];
        [self.currentParsedCharacterData appendString:string];
    }
  
}

//发现元素结束符的处理函数，保存元素各项目数据（即报告元素的结束标记）
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"item"]) {
        [self.currentParseBatch addObject:self.currentRSSItemObject];
        parseFlag = NO;
    } else if (parseFlag){
        if ([elementName isEqualToString:@"title"]) {
            self.currentRSSItemObject.title = [currentParsedCharacterData copy];
        } else if([elementName isEqualToString:@"link"]){
            self.currentRSSItemObject.link = [currentParsedCharacterData copy];
        } else if([elementName isEqualToString:@"category"]){
            self.currentRSSItemObject.category = [currentParsedCharacterData copy];
        } else if([elementName isEqualToString:@"description"]){
            self.currentRSSItemObject.description = [currentParsedCharacterData copy];
        } else if([elementName isEqualToString:@"pubDate"]){
            self.currentRSSItemObject.pubDate = [currentParsedCharacterData copy];
        } else if([elementName isEqualToString:@"content:encoded"]){
            self.currentRSSItemObject.content = [currentParsedCharacterData copy];
        }
        [currentParsedCharacterData setString:@""];
    }
}

//报告解析的结束 
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    parsed = YES;
    loading = NO;
    
}

- (void)dealloc {
    [rssItemData release];
    [currentRSSItemObject release];
    [currentParsedCharacterData release];
    [currentParseBatch release];
    
    [super dealloc];
}

@end
